<template>
	<view>
		<s-layout :onShareAppMessage="shareInfo" navbar="goods">
			<!-- 标题栏 -->
			<detailNavbar />

			<!-- 骨架屏 -->
			<detailSkeleton v-if="state.skeletonLoading" />
			<!-- 下架/售罄提醒 -->
			<s-empty v-else-if="state.goodsInfo === null" text="商品不存在或已下架" icon="/static/soldout-empty.png" showAction
				actionText="再逛逛" actionUrl="/pages/goods/list" />
			<block v-else>
				<view class="detail-swiper-selector">
					<!-- 商品轮播图  -->
					<su-swiper  isPreview :list="state.goodsSwiper" dotStyle="tag" imageMode="widthFix"
						dotCur="bg-mask-40 ss-m-b-100" :seizeHeight="750" />

					<!-- 价格+标题 -->
					<view class="title-card detail-card ss-p-y-40 ss-p-x-40">
						<view class="ss-flex ss-row-between ss-col-top ss-m-b-26">
							<view class="price-box ss-flex-1">
								<view class="price-text ss-flex ss-row-between ss-m-r-16  ss-flex-1">
									<view class="ss-flex ss-col-bottom ss-flex-1">
										<view>￥</view>
										<template v-if="state.selectedSkuPrice.price " >
											<view class="price-text-integer">{{String(state.selectedSkuPrice.price).split('.')[0]}}.</view>
											<view class="price-text-decimal">{{String(state.selectedSkuPrice.price).split('.')[1]}}</view>
										</template>
										<template v-else>
											<view class="ss-flex ss-col-bottom" v-for="(price,index) in state.goodsInfo.price" :key="price">
												<view class="ss-p-x-6" style="font-size: 44rpx;" v-if="index > 0 ">
													~
												</view>
												<view class="price-text-integer">{{String(price).split('.')[0]}}.</view>
												<view class="price-text-decimal">{{String(price).split('.')[1]}}</view>
											</view>
											<!-- {{ formatPrice(state.goodsInfo.price) }} -->
										</template>
									</view>
									<view class="shareBox" >
										<!-- <view class="shareBox-icon">
											<view class="iconBox">
												<uni-icons type="redo-filled" color="#296DDD" :size="rpx2px(20)" />
											</view>
										</view> -->
										<view class="shareBox-text ss-line-1">
											分享得3%
										</view>
									</view>
								</view>
								<view class="origin-price-text ss-m-t-15" v-if="state.goodsInfo.original_price > 0">
									{{ state.selectedSkuPrice.original_price || state.goodsInfo.original_price }}
								</view>
							</view>
							<view class="sales-text">
								{{ formatSales(state.goodsInfo.sales_show_type, state.goodsInfo.sales) }}
							</view>
						</view>
						<view class="discounts-box ss-flex ss-row-between ss-m-b-28">
							<div class="tag-content">
								<view class="tag-box ss-flex">
									<view class="tag ss-m-r-10" v-for="promos in state.goodsInfo.promos"
										:key="promos.id" @tap="onActivity">
										{{ promos.title }}
									</view>
								</view>
							</div>

							<!-- <view
                class="get-coupon-box ss-flex ss-col-center ss-m-l-20"
                @tap="state.showModel = true"
                v-if="state.couponInfo.length"
              >
                <view class="discounts-title ss-m-r-8">领券</view>
                <text class="cicon-forward"></text>
              </view> -->
						</view>
						<view class="title-text ss-line-2 ss-m-b-6">
							<image style="width: 88rpx;height: 32rpx;display:inline-block;vertical-align: middle;" :src="sheep.$url.cdn(tagInfer(state.goodsInfo))" />
						{{ state.goodsInfo.title }}</view>
						<view class="subtitle-text ss-line-1">{{ state.goodsInfo.subtitle }}</view>
					</view>
					<view class="merchant ss-flex ss-col-center"  @click="sheep.$router.go('/pages/store/shop',{id:state.goodsInfo?.store.id})">
						<image
							:src="sheep.$url.cdn(state.goodsInfo?.store?.thumb||'/static/store/shop-default-avatar.png')"
							class="avatar"></image>
						<view class=" merchant-name ss-m-r-10 ss-line-1">{{state.goodsInfo?.store?.name}}</view>
						<view class=" desc text-c-c ss-line-1">| 官方授权，100%正品</view>
					</view>
					<!-- 功能卡片 -->
					<view class="detail-cell-card detail-card ss-flex-col">
						<detail-cell-sku v-model="state.selectedSkuPrice.goods_sku_text" :skus="state.goodsInfo.skus"
							@tap="state.showSelectSku = true" />
						<detail-cell-service v-if="state.goodsInfo.service" v-model="state.goodsInfo.service" />
						<detail-cell-params v-if="state.goodsInfo.params" v-model="state.goodsInfo.params" />
					</view>


					<!-- 规格与数量弹框 -->
					<s-select-sku :goodsInfo="state.goodsInfo" :show="state.showSelectSku" @addCart="onAddCart"
						@buy="onBuy" @change="onSkuChange" @close="state.showSelectSku = false" />
				</view>

				<!-- 评价 -->
				<detail-comment-card class="detail-comment-selector" :goodsId="state.goodsId" />
				<!-- 详情 -->
				<detail-content-card class="detail-content-selector" :content="state.goodsInfo.content" />
				
				<!-- 活动跳转 -->
				<detail-activity-tip v-if="state.goodsInfo.activities" :data="state.goodsInfo"></detail-activity-tip>
				<!-- 推荐 -->
				<detailRecommendCard class="detail-recommend-selector" />
				
				<!-- 详情tabbar -->
				<detail-tabbar v-model="state.goodsInfo" :collectIcon="types==1?false:true"
					:shareIcon="types==1?false:true">
					<!-- TODO: 缺货中 已售罄 判断 设计-->

					<view class="buy-box ss-flex ss-col-center "
						v-if="state.goodsInfo.stock > 0&&state.goodsInfo.is_disabled_buy == 0&&types==''">
						<button class="ss-reset-button add-btn" @tap="state.showSelectSku = true">
							加入购物车
						</button>
						<button class="ss-reset-button buy-btn" @tap="state.showSelectSku = true">
							立即购买
						</button>
					</view>
					<view class="buy-box ss-flex ss-col-center ss-p-r-20"
						v-if="state.goodsInfo.stock <= 0 && state.goodsInfo.is_disabled_buy == 0&&types==''">
						<button class="ss-reset-button disabled-btn" disabled> 已售罄 </button>
					</view>
					<view class="buy-box ss-flex ss-col-center ss-p-r-20" v-if="types==1&&is_join==0">
						<button class="ss-reset-button add-btn disabled-btn1" @click="addmyShop(state.goodsInfo)">
							加入我的店铺 </button>
					</view>
					<view class="buy-box ss-flex ss-col-center ss-p-r-20" v-if="types==1&&is_join==1">
						<button class="ss-reset-button add-btn disabled-btn2"> 已加入店铺 </button>
					</view>
					<view class="buy-box ss-flex ss-col-center ss-p-r-20" v-if="state.goodsInfo.is_disabled_buy == 1">
						<button class="ss-reset-button disabled-btn" disabled> {{ state.goodsInfo.disabled_buy_remark }}
						</button>
					</view>
				</detail-tabbar>
				<s-coupon-get v-model="state.couponInfo" :show="state.showModel" @close="state.showModel = false"
					@get="onGet" />
				<s-activity-pop v-model="state.activityInfo" :show="state.showActivityModel"
					@close="state.showActivityModel = false" />
			</block>
		</s-layout>
	</view>
</template>

<script setup>
	import {
		watch,
		reactive,
		ref,
		computed,
		getCurrentInstance,
		onMounted,
		onBeforeMount
	} from 'vue';
	import {
		onLoad,
		onPageScroll,
		onShareTimeline
	} from '@dcloudio/uni-app';
	import sheep from '@/sheep';
	import {
		formatSales,
		formatGoodsSwiper,
		formatPrice
	} from '@/sheep/hooks/useGoods';
	import detailNavbar from './components/detail/detail-navbar.vue';
	import detailCellSku from './components/detail/detail-cell-sku.vue';
	import detailCellService from './components/detail/detail-cell-service.vue';
	import detailCellParams from './components/detail/detail-cell-params.vue';
	import detailTabbar from './components/detail/detail-tabbar.vue';
	import detailSkeleton from './components/detail/detail-skeleton.vue';
	import detailCommentCard from './components/detail/detail-comment-card.vue';
	import detailContentCard from './components/detail/detail-content-card.vue';
	import detailRecommendCard from './components/detail/detail-recommend-card.vue';
	import detailActivityTip from './components/detail/detail-activity-tip.vue';
	import {
		isEmpty
	} from 'lodash';
	import {tagInfer} from "@/sheep/helper/tools.js"
	import {
		showAuthModal
	} from '@/sheep/hooks/useModal';
	import mitt from '@/sheep/mitt.js';

	watch(()=>sheep.$store('user').isLogin,(newVal,oldVal)=>{
		if(newVal){
			addShareLog(state.goodsId , state.friend_source_id);
		}
	})
	
	onPageScroll(() => {});

	const instance = getCurrentInstance().proxy
	const eventChannel = instance.getOpenerEventChannel();
	const types = ref("")
	const store_id = ref("")
	const shopId = ref(null)
	const is_join = ref(0)
	const state = reactive({
		taskUserId: "",
		user_id: "",
		goodsId: 0,
		skeletonLoading: true,
		goodsInfo: {

		},
		showSelectSku: false,
		goodsSwiper: [],
		selectedSkuPrice: {},
		showModel: false,
		total: 0,
		couponInfo: [],
		showActivityModel: false,
		activityInfo: [],
		path:'',
		//分享
		friend_source_id:'',//朋友圈分享过来的
		im:{
			share_user_id:0,//im分享者id,
			goods_id:0,//im分享的商品id
			id:0,//分享接收者id,此id为im信息那边返回的
		},
		//分享
	});
	//分享详情
	const shareInfo = computed(() => {
		
		if (isEmpty(state.goodsInfo)) return {};
		
		console.log('shareInfo:',sheep.$platform.share.getShareInfo({
			title: state.goodsInfo.title,
			image: sheep.$url.cdn(state.goodsInfo.image),
			desc: state.goodsInfo.subtitle,
			params: {
				page: '2',
				query: state.goodsInfo.id,
				shopId: shopId.value,
			},
		}, {
			id: state.goodsInfo.id,
			type: 'goods', // 商品海报
			title: state.goodsInfo.title, // 商品标题
			image: sheep.$url.cdn(state.goodsInfo.image), // 商品主图
			price: state.goodsInfo.price[0], // 商品价格
			original_price: state.goodsInfo.original_price, // 商品原价
		}));
		 
		return sheep.$platform.share.getShareInfo({
			title: state.goodsInfo.title,
			image: sheep.$url.cdn(state.goodsInfo.image),
			desc: state.goodsInfo.subtitle,
			params: {
				page: '2',
				query: state.goodsInfo.id,
				shopId: shopId.value,
			},
		}, {
			id: state.goodsInfo.id,
			type: 'goods', // 商品海报
			title: state.goodsInfo.title, // 商品标题
			image: sheep.$url.cdn(state.goodsInfo.image), // 商品主图
			price: state.goodsInfo.price[0], // 商品价格
			original_price: state.goodsInfo.original_price, // 商品原价
		}, );
	});
	
	// 规格变更
	function onSkuChange(e) {
		state.selectedSkuPrice = e;
	}

	// 添加购物车
	function onAddCart(e) {
		//添加分享的id到购物车
		e.share_id = e.goods_id==sheep.$store('user').shareInfo.goodsId?sheep.$store('user').shareInfo.share_log_id:'';
		console.log('onAddCart----e:',e);
		sheep.$store('cart').add(e);
	}
		
	const addmyShop = async (obj) => {
		
		if (shopId.value == null || shopId.value == 0) {
			uni.showModal({
				title: '提示',
				content: '未开通权限，请先入驻商家',
				confirmText: '去申请',
				showCancel: false,
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: '/pages/store/index',

						})
					}
				}
			})
		} else {
			if (is_join.value == 0) {
				const data = {
					id: obj.id,
					store_ids: shopId.value
				}
				const {
					error,
					data1,
					mesg
				} = await sheep.$api.store.addStoreGoods(data)
				if (error == 0) {
					console.log(123, error)
					uni.showToast({
						title: '加入成功'
					})
					is_join.value = 1
					eventChannel.emit('changeStoreStatus', obj.id);
				} else {
					// uni.showToast({
					// 	title:mesg
					// })
				}
			} else {
				uni.showToast({
					title: '已加入，不能重复加入'
				})

			}
		}

	}
	// 立即购买
	function onBuy(e) {	
		
		e.share_id = e.goods_id==sheep.$store('user').shareInfo.goodsId?sheep.$store('user').shareInfo.share_log_id:'';
		
		sheep.$router.go('/pages/order/confirm', {
			data: JSON.stringify({
				order_type: 'goods',

				goods_list: [{
					goods_id: e.goods_id,
					goods_num: e.goods_num,
					goods_sku_price_id: e.id,
					share_id:e.share_id,
				}],
			}),
			taskUserId: state.taskUserId,
			shopId: shopId.value,
			user_id: state.user_id,
			store_id: store_id.value
		});
	}
	//营销活动
	function onActivity() {
		state.activityInfo = state.goodsInfo.promos;
		state.showActivityModel = true;
	}

	//立即领取
	async function onGet(id) {
		const {
			error,
			msg
		} = await sheep.$api.coupon.get(id);
		if (error === 0) {
			uni.showToast({
				title: msg,
			});
			setTimeout(() => {
				getCoupon();
			}, 1000);
		}
	}
	
	function rpx2px(rpx){
		return uni.rpx2px(rpx)
	}
	onLoad(async (options) => {
		//被分享者未登录时处理,获取分享者
		if(sheep.$store('user').shareInfo.shareId){
			if(!sheep.$store('user').shareInfo.share_log_id){
				state.friend_source_id = sheep.$store('user').shareInfo.shareId;
				showAuthModal();
			}
		}

		if (options.shopid) {
			shopId.value = options.shopid
		}
		if (options.user_id) {
			state.user_id = options.user_id
		}
		if (options.store_id) {
			store_id.value = options.store_id
		} else {
			shopId.value = sheep.$store('user').userInfo.cyq_store_id
		}
		
		//从im信息分享过来的商品
		if (options.im_id) {
			state.im.id = options.im_id;
			state.im.goods_id = options.id;
			state.im.share_user_id = options.user_id;
			await getUserInfoByImId(state.im.id);
			await addShareLog(state.im.goods_id, state.im.share_user_id);
		}
		
		if (options.types) {
			types.value = options.types
		}
		
		
		if (options.is_join) {
			is_join.value = options.is_join
		}
		
		// 非法参数
		if (!options.id) {
			state.goodsInfo = null;
			return;
		}
		if (options.taskUserId) {
			state.taskUserId = options.taskUserId
		}
		state.goodsId = options.id;
		
		//点微信朋友圈分享商品
		if(options.friend_source_id){
			state.friend_source_id = options.friend_source_id;
			if(sheep.$store('user').isLogin){
				await addShareLog(state.goodsId , options.friend_source_id);
			}else{
				showAuthModal();
			}
		}
		
		// 加载商品信息
		getGoodsDetail();
		
		//获取商品优惠券信息
		getCouponInfo();
	});
	
	//获取商品优惠券信息
	async function getCouponInfo(){
		const {
			error,
			data
		} = await sheep.$api.coupon.listByGoods(state.goodsId);
		if (error === 0) {
			state.couponInfo = data;
		}
	}
	
	// 加载商品信息
	async function getGoodsDetail(){
		
		const res = await sheep.$api.goods.detail(state.goodsId);
		
		if(res.error === 0){
			
			state.skeletonLoading = false;
			state.goodsInfo = res.data;
			state.goodsSwiper = formatGoodsSwiper(state.goodsInfo.images);
		}else{
			state.skeletonLoading = false;
			// 未找到商品
			state.goodsInfo = null;
		}
	}
	
	//根据im_id获取用户信息
	async function getUserInfoByImId(im_id) {

		const res = await sheep.$api.merchant.getUserInfoByImId({
			im_id: im_id
		});

		if (res.error == 0) {
			state.user_id = res.data.id;
		}

	}
	//添加分享记录
	async function addShareLog(goods_id, share_user_id) {
		
		let shareParams = {
			spm: `${share_user_id}.2.${goods_id}.3.1`,
			shareId: share_user_id,
			page: '/pages/goods/index',
			query: {
				id: goods_id,
			},
			platform: 'WechatMiniProgram',
			from: 'forward',
			share_log_id: '',
		};
		
		const data = await sheep.$api.user.addShareLog(shareParams);
		
		if (data && data.data && data.data.id) {
			sheep.$store('user').setShareInfo({shareId:share_user_id,goodsId:goods_id,share_log_id:data.data.id})
		}
	}

	//朋友圈分享
	onShareTimeline(() => {
		
		let user_id = sheep.$store('user').userInfo.id;
		
		if(!user_id){
			user_id = 0;
		}
		
		let title = state.goodsInfo.title;
		let imageUrl = state.goodsInfo.image;
		let goodsId = state.goodsId;
		return {
			title: title,
			query:`id=${goodsId}&friend_source_id=${user_id}`,
			imageUrl: imageUrl,
		};
	});
</script>

<style lang="scss" scoped>
	// 价格标题卡片
	.title-card {
		position: relative;
		z-index: 10;
		border-radius: 40rpx 40rpx 0 0;
		overflow: hidden;
		margin: -40rpx 0 20rpx;
		background-color: #fff;
		.price-box {
			.price-text {
				position: relative;
				color: #ff3000;
				font-family: OPPOSANS;
				font-size: 32rpx;
				line-height: 32rpx;
				font-weight: 500;
				vertical-align: bottom;
				.price-text-integer{
					font-weight: bold;
					font-size: 48rpx;
					line-height: 44rpx;
					vertical-align: bottom;
					color: #FB0036;
				}
				.price-text-decimal{
					font-weight: bold;
					font-size: 36rpx;
					line-height: 36rpx;
					vertical-align: bottom;
					color: #FB0036;
				}
			}

			.origin-price-text {
				font-size: 32rpx;
				font-weight: 500;
				text-decoration: line-through;
				color: $gray-c;
				font-family: OPPOSANS;

				&::before {
					content: '￥';
				}
			}
		}

		.sales-text {
			font-family: PingFang SC;
			font-weight: 500;
			font-size: 28rpx;
			color: #969696;
			line-height: 44rpx;
		}

		.discounts-box {
			.tag-content {
				flex: 1;
				min-width: 0;
				white-space: nowrap;
			}

			.tag-box {
				overflow: hidden;
				text-overflow: ellipsis;
			}

			.tag {
				flex-shrink: 0;
				padding: 4rpx 10rpx;
				font-size: 24rpx;
				font-weight: 500;
				border-radius: 4rpx;
				color: var(--ui-BG-Main);
				background: var(--ui-BG-Main-tag);
			}

			.discounts-title {
				font-size: 24rpx;
				font-weight: 500;
				color: var(--ui-BG-Main);
				line-height: normal;
			}

			.cicon-forward {
				color: var(--ui-BG-Main);
				font-size: 24rpx;
				line-height: normal;
				margin-top: 4rpx;
			}
		}

		.title-text {
			font-size: 30rpx;
			font-weight: bold;
			line-height: 42rpx;
		}

		.subtitle-text {
			font-size: 26rpx;
			font-weight: 400;
			color: $dark-9;
			line-height: 42rpx;
		}
	}

	// 购买
	.buy-box {
		.add-btn {
			width: 200rpx;
			height: 80rpx;
			font-weight: 500;
			font-size: 28rpx;
			border-radius: 20rpx 0 0 20rpx;
			color: $white;
			background: linear-gradient(0deg, #003194 0%, #5DB1FF 100%);
			border-radius: 12rpx 0rpx 0rpx 12rpx;
		}

		.buy-btn {
			width: 200rpx;
			height: 80rpx;
			font-weight: 500;
			font-size: 28rpx;
			color: $white;

			border-radius: 0 20rpx 20rpx 0;
			background: linear-gradient(180deg, #FFAB96 0%, #FF0F47 100%);
		}

		.disabled-btn {
			width: 400rpx;
			height: 80rpx;
			border-radius: 20rpx;
			background: #999999;
			color: $white;
		}

		.disabled-btn1 {
			width: 400rpx;
			height: 80rpx;
			border-radius: 20rpx;
			background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
			color: $white;
		}

		.disabled-btn2 {
			width: 400rpx;
			height: 80rpx;
			border-radius: 20rpx;
			background: #999999;
			color: $white;
		}
	}

	.model-box {
		height: 60vh;

		.model-content {
			height: 56vh;
		}

		.title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333333;
		}

		.subtitle {
			font-size: 26rpx;
			font-weight: 500;
			color: #333333;
		}
	}

	.merchant {

		width: calc(100% - 40rpx);
		height: 81rpx;
		margin-left: 20rpx;
		margin-right: 20rpx;
		background-image: url('https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/static/store/merchant-detail-bg.png');
		background-repeat: no-repeat;
		background-position: 0 0;
		background-size: 100% 100%;

		.avatar {
			z-index: 100;
			width: 46rpx;
			min-width: 46rpx;
			height: 46rpx;
			margin-right: 17rpx;
			margin-left: 10rpx;
		}

		.merchant-name {

			height: 43rpx;
			font-family: Source Han Sans;
			font-size: 30rpx;
			font-weight: bold;
			line-height: normal;
			letter-spacing: normal;
			color: #F2DDBF;
		}

		.desc {
			height: 43rpx;
			font-family: Source Han Sans;
			font-size: 30rpx;
			font-weight: normal;
			line-height: normal;
			letter-spacing: normal;
			color: #F2DDBF;
		}

		.text-c-c {
			min-width: 320rpx;
			justify-content: center;
			align-items: center;
		}
	}
	.shareBox{
		position: absolute;
		right: 0;
		top: 50%;
		transform: translateY(-50%);
		display: flex;
		align-items: center;
		height:50rpx;
		border-radius: 12rpx;
		background-color: rgba( 41,109,221,0.15);
		.shareBox-icon{
			height:50rpx;
			width:50rpx;
			min-width: 50rpx;
			margin-right: 12rpx;
			border-radius: 12rpx 0 20rpx 0;
			background-color: #296DDD;
			display:flex;
			align-items: center;
			justify-content: center;
			.iconBox{
				display:flex;
				align-items: center;
				justify-content: center;
				height:34rpx;
				width:34rpx;
				border-radius: 50%;
				background-color: #fff;
			}
		}
		.shareBox-text{
			padding-right: 12rpx;
			padding-left: 12rpx;
			font-size: 24rpx;
			color: #296DDD;
			vertical-align: middle;
			line-height: 1;
		}
	}
</style>